// 加载模块
const express = require('express')
// 加载自定义模块
const bd = require('./连接服务器')
// 创建 router 实例
const router = express.Router()
// 接口
// 获取文章列表
router.get('/cates', (req, res) => {
    bd(`select * from category`, (err, result) => {
        if (err) throw err
        res.send({ status: 0, message: '列表获取成功', data: result })
    })
})
// 新增文章分类
router.post('/addcates', (req, res) => {
    // 获取信息
    let { name, alias } = req.body
    // 判断数据是否存在
    bd(`select * from category where name='${name}' and alias='${alias}'`, (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            // 说明存在该分类
            res.send({ status: 1, message: '添加的分类已存在' })
        } else {
            // 新增
            bd(`insert into category set name='${name}',alias='${alias}'`, (err, result) => {
                if (err) throw err
                res.send({ status: 0, message: '新增分类成功' })
            })
        }
    })

})
// 删除文章列表
router.get('/deletecate/:id', (req, res) => {
    let { id } = req.params
    console.log(id);
    bd(`select * from category where id='${id}'`, (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            // 存在id删除
            bd(`delete from category where id='${id}'`, (err, result) => {
                if (err) throw err
                res.send({ status: 0, message: '删除成功' })
            })
        } else {
            res.send({ status: 1, message: '删除错误' })
        }
    })
})
// 根据id获取文章分类数据
router.get('/cates/:id', (req, res) => {
    let { id } = req.params
    bd(`select * from category where id='${id}'`, (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            res.send({ status: 0, message: '获取数据成功', data: result })
        } else {
            res.send({ status: 1, message: '获取数据失败' })
        }
    })
})
// 根据id更改文章分类
router.post('/updatecate', (req, res) => {
    let { id, name, alias } = req.body
    bd(`select * from category where id='${id}'`, (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            bd(`update category set name='${name}',alias='${alias}' where id='${id}'`, (err, result) => {
                if (err) throw err
                res.send({ status: 0, message: '数据替换成功' })
            })
        } else {
            res.send({ status: 1, message: '数据替换失败' })
        }
    })
})
// 输出
module.exports = router